package com.ruibang.glass.quality.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.file.FileBusiness;
import com.ruibang.glass.quality.constant.Constants;
import com.ruibang.glass.quality.domain.req.QualityGlassSizeReq;
import com.ruibang.glass.quality.domain.req.SemiCheckReportReq;
import com.ruibang.glass.quality.domain.resp.SemiCheckDetailData;
import com.ruibang.glass.quality.entity.QualityGlassSize;
import com.ruibang.glass.quality.entity.SpecsConfig;
import com.ruibang.glass.quality.feign.FileApi;
import com.ruibang.glass.quality.mapper.QualityGlassSizeMapper;
import com.ruibang.glass.quality.service.QualityGlassSizeService;
import com.ruibang.glass.quality.service.SpecsConfigService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.constant.CommonConstant;
import com.teaming.cloud.framework2.common.model.ResultBody;
import com.teaming.cloud.framework2.common.pojo.PageRequest;
import com.teaming.cloud.framework2.common.pojo.PageResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 半成品玻璃尺寸信息 服务实现类
 * </p>
 *
 * @author wujie
 * @since 2024-03-11
 */
@Service
public class QualityGlassSizeServiceImpl extends ServiceImpl<QualityGlassSizeMapper, QualityGlassSize> implements QualityGlassSizeService {

    @Autowired
    private FileApi fileApi;

//    @Autowired
//    private RedisSingleService redisService;

    @Autowired
    private RedisSingleService redisService;

    @Autowired
    private SpecsConfigService specsConfigService;

    @Override
    public void saveInfo(QualityGlassSize qualityGlassSize) {
        LocalDateTime now = LocalDateTime.now();
        if (qualityGlassSize.getTransectTime() == null) {
            qualityGlassSize.setTransectTime(now);
        }
        if (qualityGlassSize.getRecordTime() == null) {
            qualityGlassSize.setRecordTime(now);
        }
        this.save(qualityGlassSize);
        //更新文件对应业务Id
        if (CollectionUtils.isNotEmpty(qualityGlassSize.getFileIds())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setFileIds(qualityGlassSize.getFileIds());
            fileBusiness.setBusinessId(qualityGlassSize.getSizeId());
            fileApi.updateBusinessById(fileBusiness);
        }
    }

    @Override
    public void updateInfo(QualityGlassSize qualityGlassSize) {
        //更新文件信息
        if (CollectionUtils.isNotEmpty(qualityGlassSize.getDeleteFileIds())) {
            fileApi.deleteByFileIds(qualityGlassSize.getDeleteFileIds());
        }
        //新增文件
        if (CollectionUtils.isNotEmpty(qualityGlassSize.getFileIds())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setBusinessId(qualityGlassSize.getSizeId());
            fileBusiness.setFileIds(qualityGlassSize.getFileIds());
            fileApi.updateBusinessById(fileBusiness);
        }

        this.updateById(qualityGlassSize);
    }

    @Override
    public void delete(String id) {
        lambdaUpdate().eq(QualityGlassSize::getSizeId, id).set(QualityGlassSize::getIsDelete, Constants.ONE_STR).update();
    }

    @Override
    public PageResult<QualityGlassSize> queryPage(PageRequest<QualityGlassSizeReq> pageRequest) {
        final QualityGlassSizeReq param = pageRequest.getParam();
        final LambdaQueryWrapper<QualityGlassSize> lambda = new QueryWrapper<QualityGlassSize>().lambda();
        this.buildCondition(lambda, param);
        lambda.orderBy(true, false, QualityGlassSize::getTransectTime);
        final IPage<QualityGlassSize> page = this.page(new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize()), lambda);
        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
            List<String> ids = page.getRecords().stream().map(c -> c.getSizeId()).collect(Collectors.toList());
            ResultBody<List<FileBusiness>> resultBody = fileApi.getFileBusinessByIds(ids);
            Map<String, List<String>> fileMap = null;
            if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
                fileMap = resultBody.getData().stream().collect(Collectors.toMap(f -> f.getBusinessId(), f -> f.getFileIds(), (f1, f2) -> f1));
            }

            List<SpecsConfig> configs = specsConfigService.getSpecsConfigByIds(page.getRecords().stream().map(qt -> qt.getCheckRule()).collect(Collectors.toList()));
            Map<String, SpecsConfig> configMap = null;
            if (CollectionUtils.isNotEmpty(configs)) {
                configMap = configs.stream().collect(Collectors.toMap(c -> c.getSpecsId(), c -> c, (c1, c2) -> c1));
            }

            Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
            for (QualityGlassSize gs : page.getRecords()) {
                if (fileMap != null) {
                    gs.setFileIds(fileMap.get(gs.getSizeId()));
                }
                if (userMap != null) {
                    gs.setUserName(userMap.get(gs.getUserId()) == null ? "" : userMap.get(gs.getUserId()).toString());
                }
                if (configMap != null) {
                    gs.setSpecsConfig(configMap.get(gs.getCheckRule()));
                }
            }
        }

        PageResult<QualityGlassSize> pr = new PageResult(page);
        return pr;
    }

    @Override
    public List<QualityGlassSize> queryQualityGlassSize(QualityGlassSizeReq glassSizeReq) {
        final LambdaQueryWrapper<QualityGlassSize> lambda = new QueryWrapper<QualityGlassSize>().lambda();
        this.buildCondition(lambda, glassSizeReq);
        lambda.orderBy(true, true, QualityGlassSize::getTransectTime);
        List<QualityGlassSize> list = this.list(lambda);
        Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
        Map<Object, Object> productMap = redisService.hmget(RedisKey.PRODUCT_LINE_GROUP_TYPE);
        for (QualityGlassSize gs : list) {
            if (userMap != null) {
                gs.setUserName(userMap.get(gs.getUserId()) == null ? "" : userMap.get(gs.getUserId()).toString());
            }
            if (productMap != null) {
                gs.setProductLineName(productMap.get(gs.getProductLine()) == null ? "" : productMap.get(gs.getProductLine()).toString());
            }
        }
        return list;
    }

    @Override
    public List<SemiCheckDetailData> queryGlassSizeCheckData(SemiCheckReportReq reportReq) {
        return baseMapper.queryGlassSizeCheckData(reportReq);
    }


    /**
     * 构造查询条件
     *
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<QualityGlassSize> lambda, QualityGlassSizeReq param) {
        lambda.eq(QualityGlassSize::getIsDelete, CommonConstant.ZERO_STR);
        if (null == param) return;
        if (StringUtils.isNotBlank(param.getSizeId())) {
            lambda.eq(QualityGlassSize::getSizeId, param.getSizeId());
        }
        if (StringUtils.isNotBlank(param.getProductLine())) {
            lambda.eq(QualityGlassSize::getProductLine, param.getProductLine());
        }
        if (StringUtils.isNotBlank(param.getGlassId())) {
            lambda.eq(QualityGlassSize::getGlassId, param.getGlassId());
        }
        if (StringUtils.isNotBlank(param.getGlassType())) {
            lambda.eq(QualityGlassSize::getGlassType, param.getGlassType());
        }
        if (StringUtils.isNotBlank(param.getGlassModel())) {
            lambda.eq(QualityGlassSize::getGlassModel, param.getGlassModel());
        }
        if (StringUtils.isNotBlank(param.getCheckRule())) {
            lambda.eq(QualityGlassSize::getCheckRule, param.getCheckRule());
        }
        if (StringUtils.isNotBlank(param.getUserId())) {
            lambda.eq(QualityGlassSize::getUserId, param.getUserId());
        }
        if (param.getRecordStartTime() != null && param.getRecordEndTime() != null) {
            lambda.ge(QualityGlassSize::getRecordTime, param.getRecordStartTime());
            lambda.le(QualityGlassSize::getRecordTime, param.getRecordEndTime());
        }
        if (param.getTransectStartTime() != null && param.getTransectEndTime() != null) {
            lambda.ge(QualityGlassSize::getTransectTime, param.getTransectStartTime());
            lambda.le(QualityGlassSize::getTransectTime, param.getTransectEndTime());
        }
        if (StringUtils.isNotBlank(param.getTeam())) {
            lambda.eq(QualityGlassSize::getTeam, param.getTeam());
        }
        if (StringUtils.isNotBlank(param.getDecide())) {
            lambda.eq(QualityGlassSize::getDecide, param.getDecide());
        }
        if (StringUtils.isNotBlank(param.getIsRetrospect())) {
            lambda.eq(QualityGlassSize::getIsRetrospect, param.getIsRetrospect());
        }
    }
}
